<?php
class slot_controller extends controller {
  function index() {
    $slot = load('slot');
    $slots = $slot->find(array(
      'where' => 'url = %s',
      'order' => 'section, seq',
      'args' => array('oschettler')));
    $this->rendered = TRUE;
  }
  
  function save() {
    $slot_generator = load('slot');

    if (isset($_SESSION['user']) && $_SESSION['user']->url) {
      if ($this->data = $slot_generator->one(array(
        'where' => 'url = %s AND id = %d', 
        'args' => array($_SESSION['user']->url, $_POST['id'])))) {
        //D error_log("SAVE.slot " . serialize($this->data));

        $this->data->save($_POST);
      }
    }
    else {
      $_SESSION['message'] = 'Bitte melden Sie sich an, damit Ihre Änderungen gespeichert werden.';
    }

    $this->rendered = TRUE;
    $this->layout = FALSE;
    
    unset($_POST['id']);
    
    return nl2br(join(' ', $_POST));
  }
  
  function _updown($op, $slot) {

    $me = array('id' => $slot->id);
    $section = $slot->section;

    $seq = $slot->seq;
    
    $slot_generator = load('slot');

    $ids = $slot_generator->find(array(
      'fields' => array('id'),
      'where' => 'section = %s AND url = %s',
      'args' => array($slot->section, $slot->url),
      'order' => 'seq'));

    $n = count($ids);
    
    //D error_log($op . '-pre: ' . serialize($ids));

    $ix = -1;
    foreach ($ids as $i => $id) {
      if ($id['id'] == $me['id']) {
        $ix = $i;
      }
    }
    if ($ix >= 0) {
      if ($op == 'down') {
        if ($ix < $n - 1) {
          array_splice($ids, $ix, 1);
          array_splice($ids, $ix + 1, 0, array($me));
        }
      }
      else {
        if ($ix > 0) {
          array_splice($ids, $ix, 1);
          array_splice($ids, $ix - 1, 0, array($me));
        }
      }
    }
    //D error_log($op . '-post: ' . serialize($ids));
    
    foreach ($ids as $i => $id) {
      $slot->id = $id['id'];
      $slot->save(array('seq' => $i));
    }
  }

  function op() {
    $op = $this->args[1];
    $slot = $this->args[2];

    if ($op == 'del') {
      $slot->del();
    } 
    else {
      $this->_updown($op, $slot);
    }
    goto('/cv/harp/' . $slot->section);
  }
}
